
//
//  JJJUserAccount.swift
//  myBlog
//
//  Created by 姜军君 on 15/11/28.
//  Copyright © 2015年 JJJ. All rights reserved.
//

import UIKit

class JJJUserAccount: NSObject, NSCoding {
    
    // MARK: - 账户信息
    // 用于调用access_token，接口获取授权后的access token。
    var access_token:String?
    // access_token的生命周期，单位是秒数。
    var expires_in:NSTimeInterval = 0 {
        
        didSet{
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    // 过期时间
    var expiresDate:NSDate?
    // 当前授权用户的UID。
    var uid:String?
    
    // 友好显示名称
    var name:String?
    // 用户头像地址（大图），180×180像素
    var avatar_large:String?
    
    /// 字典转模型
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    /// 描述
    override var description: String {
        
        let array = ["access_token","expires_in","uid","expiresDate","name","avatar_large"]
        
        return "\(dictionaryWithValuesForKeys(array))"
    }
    
    // MARK: - 解档/归档
    // 保存路径
    static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("userAccount.plist")
 
    // 用户信息
    private static var userAccount:JJJUserAccount?
    
    /// 读取账号
    class func loadUserAccount() -> JJJUserAccount?{
        
        // 空,本地加载
        if userAccount == nil {
            
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? JJJUserAccount
        }
        // 判断过期时间
        if let account = userAccount where account.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending {
        
            userAccount = nil
        }
        
        // 返回
        return userAccount
    }
    
    /// 保存账号
    func saveUserAccount() {
        print(JJJUserAccount.accountPath)
        NSKeyedArchiver.archiveRootObject(self, toFile: JJJUserAccount.accountPath)
    }
    
    /// 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
    }
    
    /// 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(name, forKey: "name")
    }
}
